<template>
  <div class="wrapper">
    <h2 class="Title">todos</h2>
    <div class="todo-list">
      <doCase @add-item="addItem"></doCase>
      <listCase :items="items" @clear-completed="clearCompleted"></listCase>
    </div>
  </div>
</template>

<script setup>
import doCase from './doCase.vue'
import listCase from './listCase.vue'

import { ref, onMounted } from 'vue'


// 定义变量items，用于存储待办项列表
const items = ref([])

// 添加待办事项
const addItem = (text) => {
  if (text.trim()) {
    const newItem = {
      id: Date.now(),
      text: text,
      status: false,
    };
    items.value.push(newItem);
    saveItems();
  }
};



//完成数据持久化
  //定义saveItems方法，用于将items数组保存到localStorage中
const saveItems = () => {
  localStorage.setItem('items', JSON.stringify(items.value))
}
  //定义loadItems方法，用于从localStorage中加载items数组
const loadItems = () => {
  //判断localStorage中是否有items数据，有则加载，无则返回空数组
  items.value = JSON.parse(localStorage.getItem('items')?localStorage.getItem('items'):'[]')

}

const clearCompleted = () => {
  if (confirm('你确定要清除所有已完成的事项吗？')) {
    items.value = items.value.filter(item => !item.status);
    saveItems(); // 更新数据
  }
};


  //啥时候要加载数据呢？答案是组件挂载时，这个时候就用到onMounted了
onMounted(() => {
  loadItems()
})



</script>

<style>
* {
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 500px;
  height: 500px;
  margin: 0 auto;
  padding: 20px;
  background: #e5d6d6;
}
.Title {
  text-align: center;
  font-size: 50px;
}
.todo-list {
  width: 400px;
  height: 70%;
  margin: 0 auto;
  padding: 20px;
  background: white;
}

</style>

